package com.ynu.springbootappdemo.service;

import com.ynu.springbootappdemo.dao.ICartDao;
import com.ynu.springbootappdemo.dao.ISkuItemDao;
import com.ynu.springbootappdemo.model.dto.cart.SaveCartDTO;
import com.ynu.springbootappdemo.model.entity.Cart;
import com.ynu.springbootappdemo.model.entity.Customer;
import com.ynu.springbootappdemo.model.entity.SkuItem;
import com.ynu.springbootappdemo.model.entity.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Service
public class CartService {

    @Resource
    private ICartDao dao;

    @Resource
    private ISkuItemDao skuItemDao;

    @Resource
    private UserService userService;

    /**
     * 新建购物车
     * @param dto 购物车信息
     * @param request 请求
     * */
    public Cart saveCart(SaveCartDTO dto, HttpServletRequest request){
        Cart cart = new Cart();
        cart.setQuantity(dto.getCount());
        //获取登录用户
        User loginUser = userService.getLoginUser(request);
        cart.setCustomer((Customer) loginUser);
        //获取sku
        SkuItem skuItem = skuItemDao.getReferenceById(dto.getId());
        cart.setSkuItem(skuItem);
        return dao.save(cart);
    }

    public List<Cart> getAll(HttpServletRequest request){
        return dao.findAllByCustomer(userService.getLoginUser(request));
    }
}
